<template>
  <div class="Xf">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpReq"
    >
      <el-image v-if="isImg" class="avatar" :src="isImg"> </el-image>
      <span v-else class="avatar-uploader-icon">上传图片 </span>
    </el-upload>
    <span class="avatar-uploader-icon X" @click="empty">
      <i class="el-icon-circle-close"></i>
    </span>
  </div>
</template>

<script>
import cos from '@/utils/cos.js'
export default {
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 图片
      isImg: this.title
    }
  },
  methods: {
    // 文件路径
    handleAvatarSuccess(res, file) {
      this.isImg = URL.createObjectURL(file.raw)
    },
    // 文件大小校验
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 按钮 X
    empty() {
      this.isImg = ''
      this.$emit('isImgURL', this.isImg)
    },
    // 自定义上传
    httpReq({ file }) {
      cos.putObject(
        {
          Bucket: 'hr-1311150104',
          Region: 'ap-beijing',
          Key: file.name,
          Body: file,
          onProgress: progressData => {
            JSON.stringify(progressData)
          }
        },
        (err, data) => {
          if (err) {
            this.$message.error('上传失败,稍后再试试')
          }
          const url = data.Location
          this.isImg = 'https://' + url
          this.$emit('isImgURL', this.isImg)
        }
      )
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  width: 120px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 14px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
}
.Xf {
  display: block;
  position: relative;
}
.X {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #fff;
}
</style>
